import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Table,
  Space,
  Tag,
  Tooltip,
  Button,
  Modal,
  message,
  Popover,
  Switch
} from 'antd'
import { DeleteOutlined, FormOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { http } from '@/utils/http'
const { confirm } = Modal;

export default function RightList() {
  const navigate = useNavigate()
  const getRightData = async () => {
    const { data: list } = await http.get('/rights?_embed=children')
    list.forEach(item => {
      if (item.title === '首页') {
        delete item.children
      }
    })
    setDataSource(list)
  }
  useEffect(() => {
    getRightData()
  }, [])
  const [dataSource, setDataSource] = useState([])
  const [tableLoading, setTableLoading] = useState(false)

  // 展示删除确认框
  const showConfirm = item => {
    setTableLoading(true)
    confirm({
      title: '确定要删除该权限吗？',
      icon: <ExclamationCircleOutlined />,

      onOk() {
        deleteConfirm(item)
      },

      onCancel() {
        message.info('您取消了该操作！', 2)
        setTableLoading(false)
      },
    });
  }

  // 确定删除权限
  const deleteConfirm = item => {
    if (item.grade === 1) { // 如果删除的是一级权限
      setDataSource(dataSource.filter(data => data.id !== item.id))
      http.delete(`/rights/${item.id}`)
        .then(() => setTableLoading(false))
    } else if (item.grade === 2) { // 如果删除的是二级权限
      // 修改table表格绑定的数据，过滤删除的那一项
      const formatDataSource = dataSource.map(obj => {
        if (obj.id === item.rightId) {
          obj.children = obj.children.filter(f => f.id !== item.id)
        }
        return obj
      })
      // 更新状态的方法不能传原数组，必须是新数组
      setDataSource(formatDataSource)
      http.delete(`/children/${item.id}`).then(() => setTableLoading(false))
    }
    message.success('您删除了该权限，请刷新页面！', 2)
  }

  // 配置项开关
  const switchMethod = item => {
    // 对pagepermisson取反
    item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
    // item与dataSource引用同一个内存地址，item改变了，dataSource也改变了
    setDataSource([...dataSource])
    if (item.grade === 1) {
      // patch 局部更新
      http.patch(`/rights/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
        .then(() => navigate(0))
        .catch(() => {
          message.error(`更新${item.title}配置失败！`, 2)
          item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
          setDataSource([...dataSource])
        })
    } else {
      http.patch(`/children/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
        .then(() => navigate(0))
        .catch(() => {
          message.error(`更新${item.title}配置失败！`, 2)
          item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
          setDataSource([...dataSource])
        })
    }
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: id => {
        return <b>{id}</b>
      }
    },
    {
      title: '权限名称',
      dataIndex: 'title',
      key: 'title',
      align: 'center'
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      ellipsis: 'true',
      render: (_, { key }) => {
        return (
          <Tag color='magenta' key={key}>
            {key}
          </Tag>
        );
      }
    },
    {
      title: '操作',
      key: 'operate',
      align: 'center',
      render: item => {
        // console.log(item)
        return (
          <Space>
            <Tooltip title="delete" placement="left">
              <Button danger type="primary" shape="circle" icon={<DeleteOutlined />}
                onClick={() => showConfirm(item)} />
            </Tooltip>
            <Tooltip title="edit" placement="right">
              <Popover content={
                <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={item.pagepermisson}
                  onChange={() => switchMethod(item)} />
              } title="页面配置项" trigger={item.pagepermisson === undefined ? '' : 'click'}>
                <Button type="primary" shape="circle" icon={<FormOutlined />} disabled={item.pagepermisson === undefined} />
              </Popover>
            </Tooltip>
          </Space >
        )
      }
    }
  ];
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5
        }}
        expandable={{
          indentSize: 40
        }}
        loading={tableLoading}
      />
    </div>
  )
}